package com.beamfield.controller.interceptor;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;


public class SessionInterceptorAdapter extends HandlerInterceptorAdapter {

	public String[] allowUrls;

	@Value("${session.user}")
	private String user;

	@Value("${session.beam}")
	private String beam;



	public void setAllowUrls(String[] allowUrls) {
		this.allowUrls = allowUrls;
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws IOException {
//		if(LocalDateTime.now().isAfter(LocalDateTime.of(2019, 3, 15, 23, 0))){
//			return false;
//		}
		String requestUrl = request.getRequestURI().replace(request.getContextPath(), "");
		System.out.println(requestUrl);
		if (null != allowUrls && allowUrls.length >= 1) {
			for (String url : allowUrls) {
				if (requestUrl.contains(url)) {
					return true;
				}
			}
		}
		Long userid = (Long) request.getSession().getAttribute(user);
		if(userid==null||userid == 0){
//			response.sendRedirect(CommonUtils.getWebRootUrl()+"cms/login");
			response.sendRedirect(request.getContextPath()+"/cms/login");
			return false;
		}
		
		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception {

	}

}
